package com.itheima.intercept;


import com.alibaba.dubbo.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyIntercept implements HandlerInterceptor {
    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = request.getRemoteAddr();
        Jedis resource = jedisPool.getResource();
        //同一个ip一分钟之内不能访问超过多少次
        String times = resource.getSet(ip, "1");
        if (StringUtils.isNotEmpty(times)) {
            Integer t = Integer.valueOf(times);
            resource.set(ip,t+1+"");
            if(t>3){
                ServletOutputStream outputStream = response.getOutputStream();
                response.setContentType("applocation/json");//代表的是excle文件
                outputStream.write("{\"data\":null,\"flag\":false,\"message\":\"操作太频繁\"}".getBytes());
                outputStream.close();
            }
        }else {
            //这个表示一分钟之内
            resource.expire(ip,60);
        }
        resource.close();
        return true;
    }
}
